import tkinter as tk
from PIL import Image, ImageTk
import copy
import orc4
import wxchat;

list_wins=[]




def resize_image_fixed_size(original_image, factor):
    """
    将图片缩放到固定的指定尺寸（不考虑比例）
    :param image_path: 图片文件路径
    :param new_width: 缩小后的宽度（像素数）
    :param new_height: 缩小后的高度（像素数）
    :return: 缩小后的图片对象
    """
    copied_image = copy.deepcopy(original_image)

 # 这里将图片保存为PNG格式到内存缓冲区，你也可以根据实际需求换格式
    width, height = original_image.size

    new_width = int(width * factor)
    new_height = int(height * factor)
    resized_image = copied_image.resize((new_width, new_height),Image.Resampling.NEAREST)
    return resized_image
    # 示例用法，假设图片文件名为test.jpg，缩放到宽200像素、高150像素
    # image_path = "test.jpg"
    # new_width = 200
    # new_height = 150
    # resized_image = resize_image_fixed_size(image_path, new_width, new_height)


def getlastwin():
    last_index = len(list_wins) - 1
    return list_wins[last_index] if list_wins[last_index] else None

def removeDesory(_pop1):
    try:
        if _pop1 in list_wins:
            index = list_wins.index(_pop1)
            if(index>=0):
                list_wins.pop(index)
    except ValueError:
        print(f"在列表中未找到窗口 {_pop1} 的有效引用，可能已被意外移除或出现其他问题")
    finally:
        _pop1.destroy()


def getmaxy():
    max_y = None
    _win = None
    for win in list_wins:
        if (win.winfo_exists()):
            current_y = win.winfo_y()
            if max_y is None or current_y > max_y:
                max_y = current_y
                _win = win
    return _win

def getmaxx():
    max_x = None
    _win = None

    try:
        for win in list_wins:
            if(win.winfo_exists()):
                current_x = win.winfo_x()
                if max_x is None or current_x > max_x:
                    max_x = current_x
                    _win = win

        return _win
    except Exception as e:
         print('getmaxx error ',e)
         return

# (
#         scale=scale,
#         original_width=original_width,
#         original_height=original_height,
#         original_image=_options.get('image'),
#         canvas=canvas,
#         canvas_image_item=canvas_image_item
#     )


# 获取坐标
def getWinInfo(win):
    x_position = win.winfo_x() if win else 10
    # 获取弹出框在垂直方向的坐标（y坐标）
    y_position = win.winfo_y() if win else 10
    # 获取弹出框的宽度
    width = win.winfo_width() if win else 10
    # 获取弹出框的高度
    height = win.winfo_height() if win else 10
    return {"x":x_position,
            "y":y_position,
            "w": width,
            "h": height,
            }

def initdialog(root, _options,submitByDialog,userinputEvent,afterShowDialog):
    orcstr="";

    def on_entry_key(event):
        userinputnow=event.widget.get()
        print("用户正在输入：", userinputnow)
        userinputEvent(userinputnow)
    def imageshowopen():
        _options.get('image').show()
    def submit():
        user_input = entry.get()
        print(f"输入的用户信息是：{user_input}")
        submitByDialog({
             "userInput":user_input,
              "image":_options["image"],
              "orcstr":orcstr
        })
        # messagebox.showinfo("提交信息", f"你输入的内容是: {user_input}")
        # popup1.destroy()
        removeDesory(popup1)

    def cancel():
        print('取消了')
        # popup1.destroy()
        removeDesory(popup1)


    def update_image_size(*args):
        """
        根据Scale组件的值更新图片大小并在Canvas上显示
        """

        # scale_value = scale.get()  # 获取Scale组件当前的值
        # new_width = int(original_width * scale_value)
        # new_height = int(original_height * scale_value)
        # scaled_image = _options["image"].resize((new_width, new_height), Image.Resampling.LANCZOS)
        # tk_scaled_image = ImageTk.PhotoImage(scaled_image)
        # canvas.itemconfig(canvas_image_item, image=tk_scaled_image)
        # canvas.image = tk_scaled_image  # 防止图片被垃圾回收
        # canvas.config(width=new_width, height=new_height)

        # # 修改数据
        # popup1.geometry(f"{new_width}x{new_height}")

    def on_scale_release(event):
        final_value = float(scale.get())
        new_width = int(original_width * final_value)
        new_height = int(original_height * final_value)


        scaled_image = _options["image"].resize((new_width, new_height), Image.Resampling.LANCZOS)
        tk_scaled_image = ImageTk.PhotoImage(scaled_image)
        canvas.itemconfig(canvas_image_item, image=tk_scaled_image)
        canvas.image = tk_scaled_image  # 防止图片被垃圾回收
        canvas.config(width=new_width, height=new_height)

        popup1.geometry(f"{new_width}x{int(new_height)+100}")

    def show_image(*args):
        #    发送信息get dingding
        wxchat.sendImage2dingding(_options.get('image'),  entry.get())
        # img.show()

    # 新建 弹出框
    popup1 = tk.Toplevel(root)

    popup1.title(_options["title"] if _options["title"] else "提示")
    # popup1.overrideredirect(True)  # 去除窗口边框
    popup1.attributes("-topmost", True)  # 置顶窗口


    # 创建Scale组件用于调整图片缩放比例

    scale=None;
    scale = tk.Scale(popup1, from_=0.3, to=1.5, resolution=0.05, orient=tk.HORIZONTAL, command=update_image_size)
    scale.set(1)  # 设置初始值为1（即原始大小）
    # 绑定鼠标释放事件到 on_scale_release 函数
    scale.bind("<ButtonRelease>", on_scale_release)
    scale.pack()

    # 输入框
    entry = tk.Entry(popup1)
    entry.insert(0, _options["defaultValue"] if _options["defaultValue"] else "#")
    # 绑定<Key>事件到on_entry_key函数
    entry.bind("<Key>", on_entry_key)
    entry.pack()

    button_frame = tk.Frame(popup1)
    button_frame.pack()

    afterShowDialog()

    image_zoom=None;
    original_width=_options.get('image').width
    original_height = _options.get('image').height
    canvas = tk.Canvas(popup1, width=original_width, height=original_height)
    canvas.pack()
    canvas.bind("<Double-Button-1>", show_image)
    canvas_image_item=None


    try:

        # 将图片转换为适合tkinter使用的PhotoImage对象
        # image_zoom =resize_image_fixed_size(_options["image"],0.4)
        # photo = ImageTk.PhotoImage(image_zoom)
        photo = ImageTk.PhotoImage(_options["image"])
        canvas_image_item = canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        canvas.image = photo


        # label = tk.Label(popup1, image=photo)
        # label.image = photo  # 防止图片被垃圾回收
        # label.bind("<Button-1>", lambda event: show_image(_options["image"]))
        # label.pack()

    except Exception as e:
        print(f"加载图片出现错误: {e}")






    # 加入文本
    try:
        orcstr = orc4.img2text(_options.get('image'))
        # if (orcstr != ''):
            # text_widget = tk.Text(popup1)
            # # 设置文本字体为Arial，字号为12
            # text_widget.configure(font=("Arial", 12));
            # text_widget.insert(tk.END, orcstr)
            # text_widget.pack()
    except Exception as e:
       print('ocr失败',e)




    # lastwin = getlastwin()

    # x1_win=getmaxx()
    # y1_win=getmaxy();
    #
    # x1 = x1_win.winfo_x() if  x1_win else 10
    #
    #
    # y1=int(y1_win.winfo_y() if y1_win else 10)+int(y1_win.winfo_height() if y1_win else 0)+10
    #
    # print('x1==>',x1)
    # print('y1==>',y1)
    # widthxheight + x + y


    # 设置最小w h
    # width2=image_zoom.width
    # if(int(width2)<=250):
    #     width2=250
    #
    # height2=image_zoom.height
    # if(int(height2)<=100):
    #     height2=100
    #
    # screen_height = popup1.winfo_screenheight()
    # if(y1>=screen_height-180):
    #     print('最大 y')
    #     y1=screen_height - 180
    #
    #
    #
    # print("new position",x1,y1)
    # popup1.geometry(f"{width2}x{height2}")

    submit_button = tk.Button(button_frame, text="图片管理器", command=imageshowopen)
    submit_button.pack(side=tk.LEFT)

    submit_button = tk.Button(button_frame, text="确认", command=submit)
    submit_button.pack(side=tk.LEFT)

    cancel_button = tk.Button(button_frame, text="取消", command=cancel)
    cancel_button.pack(side=tk.LEFT)

    list_wins.append(popup1)


